<template>
  <div class="config-editor-layout">
    <!-- 头部工具栏 -->
    <div class="config-editor-header">
      <div class="header-left">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/configs' }">配置中心</el-breadcrumb-item>
          <el-breadcrumb-item>{{ configSchema?.name || configType }}</el-breadcrumb-item>
        </el-breadcrumb>
        <span class="config-count">
          ({{ filteredConfigs.length }} 项配置)
        </span>
      </div>
      <div class="header-right">
        <el-space>
          <el-button @click="refreshConfigs" :loading="loading">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
          <el-button @click="validateAll" :loading="validating">
            <el-icon><Check /></el-icon>
            验证全部
          </el-button>
          <el-button type="primary" @click="showCreateDialog = true">
            <el-icon><Plus /></el-icon>
            新建配置
          </el-button>
        </el-space>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="config-editor-main">
      <!-- 侧边栏：配置列表 -->
      <div class="config-editor-sidebar">
        <!-- 搜索和过滤 -->
        <div class="sidebar-toolbar">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索配置..."
            :prefix-icon="Search"
            clearable
            size="small"
          />
          
          <!-- 动态过滤器 -->
          <div v-if="filterFields.length > 0" class="filter-controls">
            <el-select
              v-for="filterField in filterFields"
              :key="filterField.key"
              v-model="filters[filterField.key]"
              :placeholder="filterField.label"
              size="small"
              clearable
              style="margin-top: 8px; width: 100%"
            >
              <el-option
                v-for="option in getFilterOptions(filterField)"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </div>
        </div>

        <!-- 配置列表 -->
        <div class="config-list">
          <div class="list-header">
            <span>配置列表</span>
            <el-dropdown @command="handleBatchAction">
              <el-button size="small" text>
                批量操作 <el-icon><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="validate">批量验证</el-dropdown-item>
                  <el-dropdown-item command="export">批量导出</el-dropdown-item>
                  <el-dropdown-item command="delete" divided>批量删除</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
          
          <div class="config-items">
            <div
              v-for="config in filteredConfigs"
              :key="getConfigId(config)"
              class="config-item"
              :class="{ 
                active: selectedConfigId === getConfigId(config),
                selected: selectedConfigs.has(getConfigId(config))
              }"
              @click="selectConfig(config)"
            >
              <div class="item-header">
                <el-checkbox
                  :model-value="selectedConfigs.has(getConfigId(config))"
                  @change="toggleSelectConfig(getConfigId(config), $event)"
                  @click.stop
                />
                <span class="item-name">{{ getConfigDisplayName(config) }}</span>
                <el-dropdown @command="handleConfigAction" trigger="click">
                  <el-button size="small" text @click.stop>
                    <el-icon><MoreFilled /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item :command="{action: 'duplicate', config}">
                        复制
                      </el-dropdown-item>
                      <el-dropdown-item :command="{action: 'export', config}">
                        导出
                      </el-dropdown-item>
                      <el-dropdown-item 
                        :command="{action: 'delete', config}" 
                        divided
                      >
                        删除
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
              
              <div class="item-meta">
                <span 
                  v-for="field in (configSchema?.listConfig?.secondaryFields || [])"
                  :key="field"
                  class="meta-tag"
                >
                  {{ config[field] }}
                </span>
              </div>
              
              <div class="item-status">
                <el-tag 
                  :type="getConfigStatus(config).type" 
                  size="small"
                  effect="plain"
                >
                  {{ getConfigStatus(config).text }}
                </el-tag>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 主编辑区 -->
      <div class="config-editor-content">
        <div v-if="!selectedConfigId" class="welcome-screen">
          <el-empty 
            description="请从左侧选择一个配置进行编辑，或创建新的配置"
            :image-size="120"
          >
            <el-button type="primary" @click="showCreateDialog = true">
              <el-icon><Plus /></el-icon>
              新建{{ configSchema?.name || '配置' }}
            </el-button>
          </el-empty>
        </div>

        <div v-else-if="configSchema" class="config-editor-form">
          <DynamicFormGenerator
            :schema="configSchema"
            v-model="selectedConfigData"
            mode="edit"
            @submit="handleConfigUpdate"
            @validate="handleConfigValidate"
            @field-change="handleFieldChange"
          />
        </div>
      </div>
    </div>

    <!-- 创建配置对话框 -->
    <el-dialog 
      v-model="showCreateDialog" 
      :title="`新建${configSchema?.name || '配置'}`"
      width="800px"
      :close-on-click-modal="false"
    >
      <DynamicFormGenerator
        v-if="configSchema"
        :schema="configSchema"
        v-model="newConfigData"
        mode="create"
        :show-actions="false"
      />
      
      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button type="primary" @click="handleConfigCreate" :loading="creating">
          创建
        </el-button>
      </template>
    </el-dialog>

    <!-- 验证结果对话框 -->
    <el-dialog 
      v-model="showValidationDialog" 
      title="验证结果" 
      width="600px"
    >
      <ValidationResultDisplay :result="validationResult" />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import type { ConfigSchema } from '@/types/schema'
import { schemaManager } from '@/utils/schema'
import DynamicFormGenerator from '@/components/DynamicFormGenerator.vue'
import ValidationResultDisplay from '@/components/ValidationResultDisplay.vue'

// 图标导入
import { 
  Refresh, Check, Plus, Search, ArrowDown, MoreFilled
} from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()

// 响应式数据
const configType = ref<string>(route.params.type as string)
const configSchema = ref<ConfigSchema>()
const configs = ref<any[]>([])
const selectedConfigId = ref<string>('')
const selectedConfigData = ref<any>({})
const newConfigData = ref<any>({})
const searchKeyword = ref('')
const filters = ref<Record<string, any>>({})
const selectedConfigs = ref(new Set<string>())

const loading = ref(false)
const validating = ref(false)
const creating = ref(false)
const showCreateDialog = ref(false)
const showValidationDialog = ref(false)
const validationResult = ref()

// 计算属性
const filteredConfigs = computed(() => {
  let result = configs.value

  // 搜索过滤
  if (searchKeyword.value && configSchema.value?.listConfig?.searchFields) {
    const keyword = searchKeyword.value.toLowerCase()
    const searchFields = configSchema.value.listConfig.searchFields
    
    result = result.filter(config => 
      searchFields.some(field => {
        const value = config[field]
        return value && String(value).toLowerCase().includes(keyword)
      })
    )
  }

  // 动态过滤器
  for (const [filterKey, filterValue] of Object.entries(filters.value)) {
    if (filterValue) {
      result = result.filter(config => config[filterKey] === filterValue)
    }
  }

  return result
})

const filterFields = computed(() => {
  if (!configSchema.value?.listConfig?.sortFields) return []
  
  return configSchema.value.fields.filter(field => 
    configSchema.value!.listConfig!.sortFields.includes(field.key) &&
    field.type === 'select'
  )
})

// 方法
const getConfigId = (config: any) => {
  if (!configSchema.value) return ''
  
  // 尝试常见的ID字段
  const idFields = ['id', 'skillId', 'key', 'name']
  for (const field of idFields) {
    if (config[field]) return config[field]
  }
  
  return config[configSchema.value.listConfig?.primaryField || 'name']
}

const getConfigDisplayName = (config: any) => {
  if (!configSchema.value?.listConfig?.primaryField) return '未知配置'
  return config[configSchema.value.listConfig.primaryField] || '未命名'
}

const getConfigStatus = (config: any) => {
  if (!configSchema.value?.listConfig?.statusField) {
    return { type: 'info', text: '正常' }
  }
  
  const statusValue = config[configSchema.value.listConfig.statusField]
  
  if (typeof statusValue === 'boolean') {
    return statusValue 
      ? { type: 'success', text: '启用' }
      : { type: 'info', text: '禁用' }
  }
  
  // 根据状态值映射
  const statusMap: Record<string, { type: string, text: string }> = {
    'healthy': { type: 'success', text: '健康' },
    'warning': { type: 'warning', text: '警告' },
    'error': { type: 'danger', text: '错误' },
    'enabled': { type: 'success', text: '启用' },
    'disabled': { type: 'info', text: '禁用' }
  }
  
  return statusMap[statusValue] || { type: 'info', text: String(statusValue) }
}

const getFilterOptions = (field: any) => {
  if (field.options) return field.options
  
  // 从现有配置中提取唯一值
  const uniqueValues = [...new Set(configs.value.map(config => config[field.key]))]
  return uniqueValues.filter(Boolean).map(value => ({
    label: String(value),
    value: value
  }))
}

const selectConfig = (config: any) => {
  const configId = getConfigId(config)
  selectedConfigId.value = configId
  selectedConfigData.value = { ...config }
}

const toggleSelectConfig = (configId: string, selected: boolean) => {
  if (selected) {
    selectedConfigs.value.add(configId)
  } else {
    selectedConfigs.value.delete(configId)
  }
}

const handleConfigUpdate = (updatedData: any) => {
  // 更新配置数据
  const index = configs.value.findIndex(config => 
    getConfigId(config) === selectedConfigId.value
  )
  
  if (index !== -1) {
    configs.value[index] = { ...updatedData }
    ElMessage.success('配置更新成功')
  }
}

const handleConfigCreate = async () => {
  if (!configSchema.value) return
  
  creating.value = true
  try {
    // 验证配置数据
    const validation = schemaManager.validateData(configType.value, newConfigData.value)
    if (!validation.valid) {
      ElMessage.error('配置验证失败: ' + validation.errors.join(', '))
      return
    }
    
    // 添加到配置列表
    configs.value.push({ ...newConfigData.value })
    showCreateDialog.value = false
    
    // 选中新创建的配置
    selectedConfigId.value = getConfigId(newConfigData.value)
    selectedConfigData.value = { ...newConfigData.value }
    
    // 重置表单
    newConfigData.value = {}
    
    ElMessage.success(`${configSchema.value.name}创建成功`)
  } catch (error) {
    ElMessage.error('创建失败')
  } finally {
    creating.value = false
  }
}

const handleConfigValidate = (result: any) => {
  validationResult.value = result
  if (!result.valid) {
    showValidationDialog.value = true
  }
}

const handleFieldChange = (field: string, value: any) => {
  // 字段变更时的处理逻辑
  console.log(`字段 ${field} 变更为:`, value)
}

const handleConfigAction = ({ action, config }: { action: string, config: any }) => {
  const configId = getConfigId(config)
  
  switch (action) {
    case 'duplicate':
      const duplicated = {
        ...config,
        [configSchema.value?.listConfig?.primaryField || 'name']: 
          `${getConfigDisplayName(config)} (副本)`,
        id: `${configId}_copy_${Date.now()}`
      }
      configs.value.push(duplicated)
      selectedConfigId.value = getConfigId(duplicated)
      selectedConfigData.value = { ...duplicated }
      ElMessage.success('配置复制成功')
      break
      
    case 'export':
      exportConfig(config)
      break
      
    case 'delete':
      deleteConfig(configId)
      break
  }
}

const handleBatchAction = (action: string) => {
  const selectedIds = Array.from(selectedConfigs.value)
  if (selectedIds.length === 0) {
    ElMessage.warning('请先选择要操作的配置')
    return
  }
  
  switch (action) {
    case 'validate':
      // 批量验证
      break
    case 'export':
      // 批量导出
      break
    case 'delete':
      // 批量删除
      ElMessageBox.confirm(
        `确定要删除选中的 ${selectedIds.length} 个配置吗？`,
        '批量删除确认',
        { type: 'warning' }
      ).then(() => {
        configs.value = configs.value.filter(config => 
          !selectedIds.includes(getConfigId(config))
        )
        selectedConfigs.value.clear()
        selectedConfigId.value = ''
        ElMessage.success('批量删除成功')
      })
      break
  }
}

const exportConfig = (config: any) => {
  const blob = new Blob([JSON.stringify(config, null, 2)], { 
    type: 'application/json' 
  })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `${getConfigDisplayName(config)}.json`
  a.click()
  URL.revokeObjectURL(url)
}

const deleteConfig = (configId: string) => {
  ElMessageBox.confirm(
    '确定要删除这个配置吗？此操作不可撤销。',
    '确认删除',
    { type: 'warning' }
  ).then(() => {
    configs.value = configs.value.filter(config => 
      getConfigId(config) !== configId
    )
    if (selectedConfigId.value === configId) {
      selectedConfigId.value = ''
    }
    ElMessage.success('配置删除成功')
  })
}

const refreshConfigs = async () => {
  loading.value = true
  try {
    // 这里应该从服务器加载配置数据
    // 暂时使用模拟数据
    await loadMockData()
    ElMessage.success('配置刷新成功')
  } catch (error) {
    ElMessage.error('配置刷新失败')
  } finally {
    loading.value = false
  }
}

const validateAll = async () => {
  validating.value = true
  try {
    // 验证所有配置
    const errors: string[] = []
    
    for (const config of configs.value) {
      const validation = schemaManager.validateData(configType.value, config)
      if (!validation.valid) {
        errors.push(`${getConfigDisplayName(config)}: ${validation.errors.join(', ')}`)
      }
    }
    
    if (errors.length === 0) {
      ElMessage.success(`验证通过！检查了 ${configs.value.length} 个配置`)
    } else {
      validationResult.value = {
        valid: false,
        errors: errors,
        validatedCount: configs.value.length
      }
      showValidationDialog.value = true
    }
  } catch (error) {
    ElMessage.error('验证失败')
  } finally {
    validating.value = false
  }
}

const loadMockData = async () => {
  // 模拟数据加载
  if (configType.value === 'equipment') {
    configs.value = [
      {
        id: 'sword_001',
        name: '铁剑',
        sys: '现代',
        type: '武器',
        job: '血骑士',
        solt: '主手',
        emoji: '⚔️',
        enabled: true,
        quality: { min: 1, max: 3 },
        baseAttributes: []
      },
      {
        id: 'shield_001',
        name: '铁盾',
        sys: '现代',
        type: '防具',
        job: '血骑士',
        solt: '副手',
        emoji: '🛡️',
        enabled: true,
        quality: { min: 2, max: 4 },
        baseAttributes: []
      }
    ]
  } else if (configType.value === 'skill') {
    configs.value = [
      {
        skillId: 'slash_001',
        name: '普通斩击',
        type: 'active',
        quality: 1,
        cooldown: 0,
        maxLevel: 5,
        enabled: true
      },
      {
        skillId: 'heal_001',
        name: '治疗术',
        type: 'active',
        quality: 2,
        cooldown: 1,
        maxLevel: 10,
        enabled: true
      }
    ]
  }
}

// 监听器
watch(() => route.params.type, (newType) => {
  if (newType) {
    configType.value = newType as string
    configSchema.value = schemaManager.getSchema(configType.value)
    refreshConfigs()
  }
}, { immediate: true })

watch(() => showCreateDialog.value, (show) => {
  if (show && configSchema.value) {
    // 初始化新配置数据
    newConfigData.value = {}
    for (const field of configSchema.value.fields) {
      if (field.defaultValue !== undefined) {
        newConfigData.value[field.key] = field.defaultValue
      }
    }
  }
})

// 生命周期
onMounted(() => {
  configSchema.value = schemaManager.getSchema(configType.value)
  if (configSchema.value) {
    refreshConfigs()
  } else {
    ElMessage.error(`未找到类型 ${configType.value} 的配置Schema`)
    router.push('/configs')
  }
})
</script>

<style scoped>
.sidebar-toolbar {
  padding: 16px;
  border-bottom: 1px solid var(--config-editor-border);
}

.filter-controls {
  margin-top: 8px;
}

.config-list {
  flex: 1;
  overflow-y: auto;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid var(--config-editor-border);
  font-weight: 600;
  color: var(--config-editor-text);
}

.config-items {
  padding: 8px;
}

.config-item {
  padding: 12px;
  margin-bottom: 8px;
  border: 1px solid var(--config-editor-border);
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s;
  background: var(--config-editor-card-bg);
}

.config-item:hover {
  border-color: var(--config-editor-primary);
}

.config-item.active {
  border-color: var(--config-editor-primary);
  background: rgba(64, 158, 255, 0.1);
}

.config-item.selected {
  background: rgba(64, 158, 255, 0.05);
}

.item-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.item-name {
  flex: 1;
  font-weight: 500;
  color: var(--config-editor-text);
  font-size: 14px;
}

.item-meta {
  display: flex;
  gap: 6px;
  margin-bottom: 8px;
  flex-wrap: wrap;
}

.meta-tag {
  padding: 2px 6px;
  background: var(--config-editor-border);
  border-radius: 4px;
  font-size: 11px;
  color: var(--config-editor-text-secondary);
}

.item-status {
  text-align: right;
}

.welcome-screen {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.config-editor-form {
  height: 100%;
  overflow-y: auto;
  padding: 20px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.config-count {
  color: var(--config-editor-text-secondary);
  font-size: 14px;
}

.header-right {
  display: flex;
  align-items: center;
}
</style>
